<?php
class Forbid
{
    var $allow_time = 120; //防刷新时间
    var $allow_num = 2; //防刷新次数
    var $allow_max = 10; //在超过最大次数后，加入永久禁止IP名单
    var $logfile_path = './log/'; //日志文件保存目录
    var $fileht = './.htaccess2'; //永久禁止IP名单

    var $is_forbid = false;
    var $is_always_forbid = false;
    var $ip, $url, $time;

    function __construct()
    {
        $this->ip = $_SERVER['REMOTE_ADDR'];
        $this->url = $_SERVER['PHP_SELF']; //去除参数的URL
        $this->time = time();

        if (!is_file($this->fileht)) {
            file_put_contents($this->fileht, '');
        }
        $filehtarr = file($this->fileht);
        if (in_array($this->ip . "\r\n", $filehtarr)) {
            $this->is_forbid = true;
            $this->is_always_forbid = true; //永久禁止访问
            return; //不再进行访问记录的更新操作
        }
        
        $file = $this->logfile_path . 'ipdate.dat'; //访问记录
        if (!is_dir($this->logfile_path)) {
            mkdir($this->logfile_path, 0777);
        }
        if (!is_file($file)) {
            file_put_contents($file, '');
        }

        $check_ip = md5($this->ip);
        $check_url = md5($this->url);
        $yes_no = true; //记录是否为初次访问
        $str = '';
        $ipdate = file($file);
        foreach ($ipdate as $k => $v) {
            $item_ip = substr($v, 0, 32);
            $item_url = substr($v, 32, 32);
            $item_time = substr($v, 64, 10);
            $item_num = intval(substr($v, 74));
            if ($this->time - $item_time < $this->allow_time) {
                if ($item_ip != $check_ip) {
                    $str .= $v;
                } else { //再次访问
                    $yes_no = false;
                    if ($item_url != $check_url) { //请求的URL不同
                        $str .= $item_ip . $check_url . $this->time . "1\r\n";
                    } else {
                        if ($item_num < $this->allow_num) { //在允许次数内
                            $str .= $item_ip . $item_url . $item_time . ($item_num + 1) . "\r\n";
                        } else {
                            $this->is_forbid = true; //禁止访问
                            $line = $this->ip . '--' . date('Y-m-d H:i:s', time()) . '--' . $this->url . "--" . ($item_num + 1) . "\r\n";
                            file_put_contents($this->logfile_path . 'forbid.log', $line, FILE_APPEND);
                            if ($item_num < $this->allow_max) { //未超过最大刷新次数
                                $str .= $item_ip . $item_url . $item_time . ($item_num + 1) . "\r\n";
                            } else {
                                file_put_contents($this->fileht, $this->ip . "\r\n", FILE_APPEND);
                            }
                        }
                    }
                }
            }
        }
        if ($yes_no) //初次访问
            $str .= $check_ip . $check_url . $this->time . "1\r\n";
        file_put_contents($file, $str);
    }

    function isForbid() {
        return $this->is_forbid;
    }
}